package com.recruit.g1.user.base.exception;

import com.recruit.g1.user.base.response.JsonResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JsonResult<Object> handleException(Exception e) {
        e.printStackTrace();
        return JsonResult.fail("系统异常: " + e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public JsonResult<Object> handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return JsonResult.fail("运行时异常: " + e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .findFirst()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .orElse("参数验证失败");
        return JsonResult.fail(errorMessage);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult<Object> handleConstraintViolationException(ConstraintViolationException e) {
        return JsonResult.fail("参数验证异常: " + e.getMessage());
    }

    // 可以根据需要添加更多特定异常的处理
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult<Object> handleIllegalArgumentException(IllegalArgumentException e) {
        return JsonResult.fail("非法参数: " + e.getMessage());
    }
}